package sessionutil

import (
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/jwtutil"
	"strconv"
)

func CheckAdminLogin(userId int64) bool {
	return dao.GetRedisCli().HExists(constant.CacheKeySysUserSessionMap, strconv.FormatInt(userId, 10)).Val()
}

func AdminLogout(userId int64) bool {
	return dao.GetRedisCli().HDel(constant.CacheKeySysUserSessionMap, strconv.FormatInt(userId, 10)).Val() == 1
}

func SetSysUserSession(user *entity.SysUser) string {
	token := jwtutil.GenToken(&jwtutil.JwtClaims{
		UserId: user.Id,
		ShopId: user.ShopId,
	}, int64(3600*24*7))
	SetSysUserCache(user)
	seelog.Debug("[add sysUser session], token=" + token)
	return token
}

func SetSysUserCache(user *entity.SysUser) {
	dao.GetRedisCli().HSet(constant.CacheKeySysUserSessionMap, strconv.FormatInt(user.Id, 10), convertutil.ToJsonString(user))
}

// GetSysUserInfo 获取用户信息, 可以加层缓存
func GetSysUserInfo(userId int64) *entity.SysUser {
	user := new(entity.SysUser)
	result, err := dao.GetRedisCli().HGet(constant.CacheKeySysUserSessionMap, strconv.FormatInt(userId, 10)).Result()
	if err != nil {
		convertutil.ParseJson(result, user)
	}
	if user.Id == userId {
		return user
	}

	if err := dao.GetDB().Model(user).Where("id", userId).Take(user).Error; err != nil {
		seelog.Errorf("fail to search user from db, err: %v", err)
		return user
	}
	// 拉取权限信息
	user.PermissionSet = map[string]interface{}{}
	user.ParseRoleList()
	for _, roleId := range user.RoleIdList {
		role := &entity.SysRole{}
		dao.GetDB().Table(entity.TableNameSysRole).Where("id", roleId).Take(role)
		if role.Id == 0 {
			continue
		}
		if len(user.RoleNames) > 0 {
			user.RoleNames += ","
		}
		user.RoleNames += role.Name
		role.ParsePermissionList()
		for _, permission := range role.PermissionList {
			user.PermissionSet[permission] = true
		}
	}
	SetSysUserCache(user)
	return user
}

// GetSysUserIdFromCtx see midware.Auth() and jwtutil.JwtClaims
func GetSysUserIdFromCtx(ctx *gin.Context) int64 {
	return ctx.GetInt64(constant.ParamSysUserId)
}
